import React from 'react';
import map from 'lodash/map';
import omit from 'lodash/omit';
import { Col, Form } from 'antd';


export const createForm = () => {
  return (Comp) => {
    class WithDetailForm extends React.Component {

      constructor(props) {
        super(props);
      }

      getFields(formFields, colSpanDefault, formItemPropsDefault = {}) {
        const colSpan = colSpanDefault ? colSpanDefault :
          (formFields.length > (this.props.fromLineLeg ? this.props.fromLineLeg : 5) ? 12 : 24);
        const formItemProps = {
          labelCol: { span: 7 },
          wrapperCol: { span: 16 },
          ...formItemPropsDefault,
        };
        const { getFieldDecorator } = this.props.form;

        return map(formFields, (fItem, fKey) => (
          <Col span={colSpan} key={fKey}>
            <Form.Item {...formItemProps} label={fItem.label} {...(fItem.itemProps || {})}>
              {getFieldDecorator(fItem.fieldName, fItem.options)(
                fItem.comp,
              )}
            </Form.Item>
          </Col>
        ));
      }

      render() {
        const compProps = {
          ...omit(this.props, ['forwardRef']),
          getFields: this.getFields.bind(this),
        };
        return (
          <Comp ref={this.props.forwardRef} {...compProps} />
        );
      }
    }

    WithDetailForm.displayName = `WithDetailForm(${Comp.displayName || Comp.name})`;
    return React.forwardRef((props, ref) => {
      return <WithDetailForm {...props} forwardRef={ref}/>;
    });
  };
};
